const Role = require("../../model/user/role")
const Rule = require("../../model/user/rule")
// 引入外部模块 获取当前时间
const { getTime } = require("../../utils/gettime")
// // 引入 nanoid 生成唯一字符串
// const { nanoid } = require("nanoid")

// 根据id查询角色
exports.getRoleById = async ({ id }) => {
    try {
        if (!id) return { msg: "查询失败", code: "400" }
        let res = await Role.findOne({
            attributes: ["id", "rolename", "rolekey", "rolestatus", "isdelete", "creator"],
            where: { id }
        })
        // 将角色权限转化为数组
        res.rolekey = res.rolekey.split(",")
        if (!res) return { msg: "没有您要查找的角色", code: "400" }
        return { msg: "查询成功", code: "200", data: res }
    } catch (err) { return { msg: "查询失败", code: "200", err } }
}

// 查询角色列表
exports.getRoleList = async ({ pageNum, pageSize }) => {
    try {
        pageNum = pageNum.replace(/\s*/g, "");
        pageSize = pageSize.replace(/\s*/g, "");
        if (!pageNum) return { msg: "查询失败 pageNum is undefind", code: "400" }
        if (!pageSize) return { msg: "查询失败 pageSize is undefind", code: "400" }
        pageNum = Number(pageNum) || 1
        pageSize = Number(pageSize) || 5
        if (!isNaN(pageNum) && !isNaN(pageSize)) {
            let res = await Role.findAndCountAll({
                offset: pageNum * pageSize - pageSize,
                limit: pageSize,
                attributes: ["id", "rolename", "rolekey", "isdelete", "creator", "rolestatus"]
            })
            // 将角色权限转化为数组
            res.rows.forEach(item => {
                item.rolekey = item.rolekey.split(",")
            })
            return { msg: "查询成功", code: "200", data: res }
        }else{
            return {msg:"获取失败 pageNum or pageSize is undefind",code:"400"}
        }
    } catch (err) { return { msg: "查询失败", code: "200", err } }
}

// 添加角色
exports.createRole = async ({ rolename, rolekey, creator }) => {
    try {
        rolekey = rolekey.toString()
        if (!rolename) return { msg: "添加失败 rolename is undefind", code: "400" }
        if (!rolekey) return { msg: "添加失败 rolekey is undefind", code: "400" }
        let isCreate = await Role.findOne({ where: { rolename } })
        if (isCreate) return { msg: "添加失败 角色名重复", code: "400" }
        let newData = {}
        if (rolename) newData.rolename = rolename;
        if (rolekey) newData.rolekey = rolekey;
        if (creator) newData.creator = creator;
        newData.createdate = getTime();
        let createRole = await Role.create(newData)
        if (createRole) {
            let getRuleByRolekey = rolekey.split(",")
            let rules = await Rule.findAll({
                where: { rulename: getRuleByRolekey }
            })
            await createRole.addRule(rules)
            let res = await Role.findOne({
                attributes: ["id", "rolename", "rolekey", "createdate", "creator"],
                where: { rolename },
                include: [{
                    attributes: ["rulename", "summary", "id"],
                    model: Rule
                }]
            })
            return { msg: "添加角色成功", code: "200", data: res }
        } else {
            return { msg: "添加角色失败", code: "400" }
        }
    } catch (err) {
        return { msg: "添加角色失败", code: "400", err }
    }
}

// 编辑角色
exports.editRole = async ({ id, rolename, rolekey, rolestatus, isdelete, remark, updator }) => {
    try {
        if (!id) return { msg: "编辑失败", code: "400" }
        let newData = {};
        if (rolestatus) newData.rolestatus = rolestatus;
        if (isdelete) newData.isdelete = isdelete;
        if (rolename) newData.rolename = rolename;
        if (remark) newData.remark = remark;
        newData.update = getTime();
        if (updator) newData.updator = updator;
        let isUpdate = await Role.update(newData, {
            where: { id }
        })
        newData = {};
        if (isUpdate) {
            let event = await Role.findOne({ where: { id } })
            let getRuleByRolekey = rolekey.split(",")
            let rules = await Role.findOne({
                where: { id },
                include: [{
                    model: Rule,
                    attributes: ["rulename"]
                }]
            })
            let ruleId = rules.Rules.map(item => item.rulename)
            let list = getRuleByRolekey.filter(item => {
                return ruleId.indexOf(item) === -1
            })
            let rulesList = await Rule.findAll({
                where: { rulename: list }
            })
            await event.addRule(rulesList)

            let res = await Role.findOne({
                where: { id },
                attributes: ["id", "rolename", "createdate", "creator", "update", "updator"]
            })
            return { msg: "编辑成功", code: "200", data: res }
        } else {
            return { msg: "编辑失败", code: "400" }
        }
    } catch (err) { return { msg: "编辑失败", code: "400", err } }
}

// 删除角色
exports.removeRole = async ({ id }) => {
    try {
        if (!id) return { msg: "删除失败 id in undefind", code: "400" }
        let isRemove = await Role.destroy({ where: { id } })
        if (isRemove) return { msg: "删除成功", code: "200" }
        return { msg: "删除失败", code: "400" }
    } catch (err) { return { msg: "删除失败", code: "400", err } }
}